﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Wx.Sdk.Api.Entity.Base;
using Wx.Sdk.MiniProgram.Entity;
using Wx.Sdk.Ext;
using Wx.Sdk.Utils;

namespace Wx.Sdk.MiniProgram.Base
{
    internal class MiniProgramBase
    {
        WxMiniProgram wxApp;
        internal MiniProgramBase(WxMiniProgram wxApp)
        {
            this.wxApp = wxApp;
        }
        /// <summary>
        /// 获取微信小程序的AccessToken
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task<string> GetAccessToken()
        {
            var key = $"WeChatApplicationWithAccessToken_{wxApp.appOption.appid}";
            //获取缓存中的值
            var tokenCache = wxApp.wxCache.Get<string>(key);
            if (tokenCache.IsNull())
            {
                var url = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={wxApp.appOption.appid}&secret={wxApp.appOption.secret}";
                var str = await Get(url);
                var accessToken = JsonHelper.ToModel<AccessToken>(str);
                Contract.Assume(accessToken != null);
                if (accessToken.Errcode != 0) throw new WxError($"{accessToken.Errcode}=>{accessToken.Errmsg}");
                tokenCache = accessToken.access_token;
                //存入缓存,绝对过期时间
                wxApp.wxCache.Set(key, tokenCache, accessToken.expires_in - 100);
            }
            return tokenCache;
        }
        /// <summary>
        /// GET数据
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public async Task<string> Get(string url)
        {
            Contract.Assume(!url.IsNull());
            var client = wxApp.httpClientFactory.CreateClient();
            //远程拉取字符串
            var data = await client.GetStringAsync(url);
            var msg = JsonHelper.ToModel<WxResponseMsg>(data) ?? new WxResponseMsg();
            if (msg.Errcode != 0) throw new WxError($"{msg.Errcode}=>{msg.Errmsg}");
            return data;
        }
        /// <summary>
        /// POST数据
        /// </summary>
        /// <param name="body"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public async Task<string> Post(string body, string url)
        {
            Contract.Assume(!url.IsNull());
            var client = wxApp.httpClientFactory.CreateClient();
            var content = new StringContent(body);
            var responseMsg = await client.PostAsync(url, content);
            var data = await responseMsg.Content.ReadAsStringAsync();
            var msg = JsonHelper.ToModel<WxResponseMsg>(data) ?? new WxResponseMsg();
            if (msg.Errcode != 0) throw new WxError($"{msg.Errcode}=>{msg.Errmsg}");
            return data;
        }
        public async Task<byte[]> PostByte(string body, string url)
        {
            Contract.Assume(!url.IsNull());
            var client = wxApp.httpClientFactory.CreateClient();
            var content = new StringContent(body);
            var responseMsg = await client.PostAsync(url, content);
            var data = await responseMsg.Content.ReadAsByteArrayAsync();
            var str = System.Text.Encoding.UTF8.GetString(data);
            if (str.IsNull()) throw new WxError("微信回传信息为空");
            var msg = JsonHelper.ToModel<WxResponseMsg>(str) ?? new WxResponseMsg();
            if (msg.Errcode != 0) throw new WxError($"{msg.Errcode}=>{msg.Errmsg}");
            return data;
        }
    }
}
